<?php

/**
 * 关键字控制器
 *
 * @author mengyuwang
 */

require_once 'CommonController.php';

class Admin_PartnerToolController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_ProductOrder();
        $this->_productModel = new Application_Model_PartnerProduct();
        $this->_productPlatformModel = new Application_Model_ProductPlatform();
        $this->_cbeModel = new Application_Model_ClientBootExport();
        $this->_sModel = new Application_Model_Source();
        $this->_ddwModel = new Application_Model_DayDataWap();
        $this->view->title = "管理中心";
    }

    /**
     * 列表
     * 
     * @return void
     */
    public function indexAction()
    {          
        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }
        
        //设置URL模板
        $urls = array();
        $wheres = array();
        $countDate = trim($this->_request->get('startTime'));//关键字
        $this->view->countDate = $countDate;
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        
        if ($countDate != '') {//按照关键字搜索
             $urls['countDate'] = $countDate;
             $wheres[] = "`countDate` = '" . addslashes($countDate) . "'";
        }
        if ($productCode != '') {//按照产品编号搜索
             $wheres[] = "`productCode` LIKE '" . addslashes($productCode). "'"; 
        }
        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
       
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';      
        $sql = "SELECT * 
            FROM `{$this->_model->getTableName()}` 
            {$where} 
            ORDER BY `countDate` desc
        ";
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');

        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();      
        $this->view->rows = $dbPaginator->getRows();
        $urls['pageNo'] = $pageNo;
        $urls['action']='index';
        $this->view->pageUrl = $this->view->projectUrl($urls);
    }
    

    /**
     * 添加动作
     * 
     * @return void
     */
    public function insertAction()
    {
        $this->view->subtitle='添加订单记录(按日统计)';
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $this->view->product = $this->_productModel->fetchRow("code = '{$productCode}'");
        $this->view->osNames = $this->_productPlatformModel->fetchAll("productCode = '{$productCode}'");
        
        if ($this->_request->isPost()) {
            $row = array();
            $filter = new Zend_Filter_StripTags();            
            $row['countDate'] = $filter->filter(trim($this->_request->getPost('startTime')));
            $row['osName'] = $filter->filter(trim($this->_request->getPost('osName')));
            $row['orderNum'] = intval($filter->filter(trim($this->_request->getPost('orderNum'))));
            $row['orderAmount'] = floatval($filter->filter(trim($this->_request->getPost('orderAmount'))));
            $row['orderPerprice'] = floatval($filter->filter(trim($this->_request->getPost('orderPerprice'))));
            $row['productCode'] = $productCode;
            $row['addTime'] = date('Y-m-d H:i:s');
            
            if (strlen($row['osName']) < 0) {
            	echo $this->view->message('必须选择操作系统，请重新填写！') ;
                exit;
            }        
            if (strlen($row['countDate']) < 1) {
                echo $this->view->message('必须选择统计时间，请重新填写！') ;
                exit;
            }
            if ($row['orderNum'] <= 0) {
                echo $this->view->message('订单数量必须大于0，请重新填写。') ;
                exit; 
            }
            if ($row['orderAmount'] <= 0) {
                echo $this->view->message('订单金额必须大于0，请重新填写。') ;
                exit; 
            }
            if ($row['orderPerprice'] <= 0) {
                echo $this->view->message('客单价必须大于0，请重新填写。') ;
                exit; 
            }
            if ($this->_model->isExists($row)) {
                echo $this->view->message('已经存在相同的日期和产品的组合，请重新填写。');
                exit; 
            }
            $this->_model->insert($row);
            echo $this->view->message('操作成功！', $this->view->projectUrl(array('action' => 'index'))) ;
            exit;
        }
        $this->renderScript('partner-tool/edit.php');
    }

    /**
     * 更新动作
     * 
     * @return void
     */
    public function updateAction()
    {
        $id = intval($this->_request->get('id'));
        $this->view->subtitle='修改客户订单';
        if (empty($id)) {
             throw new Exception('Invalid params!');
        }
        $this->view->row = $this->_model->fetchRow("`id` = {$id}"); 
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $this->view->product = $this->_productModel->fetchRow("code = '{$productCode}'");
        $this->view->osNames = $this->_productPlatformModel->fetchAll("productCode = '{$productCode}'");
        if ($this->_request->isPost()) {
            $row = array();
            $filter = new Zend_Filter_StripTags();
            $row['osName'] = $filter->filter(trim($this->_request->getPost('osName')));
            $row['countDate'] = $filter->filter(trim($this->_request->getPost('startTime')));
            $row['orderNum'] = intval($filter->filter(trim($this->_request->getPost('orderNum'))));
            $row['orderAmount'] = floatval($filter->filter(trim($this->_request->getPost('orderAmount'))));
            $row['orderPerprice'] = floatval($filter->filter(trim($this->_request->getPost('orderPerprice'))));
            $row['productCode'] = $productCode;
            
            if (strlen($row['osName']) < 0) {
            	echo $this->view->message('必须选择操作系统，请重新填写！') ;
                exit;
            }
            if (strlen($row['countDate']) < 1) {
                echo $this->view->message('必须选择统计时间，请重新填写！') ;
                exit;
            }
            if ($row['orderNum'] <= 0) {
                echo $this->view->message('订单数量必须大于0，请重新填写。') ;
                exit; 
            }
            if ($row['orderAmount'] <= 0) {
                echo $this->view->message('订单金额必须大于0，请重新填写。') ;
                exit; 
            }
            if ($row['orderPerprice'] <= 0) {
                echo $this->view->message('客单价必须大于0，请重新填写。') ;
                exit; 
            }
            if ($this->_model->isExists($row, $id)) {
                echo $this->view->message('已经存在相同的日期和产品的组合，请重新填写。');
                exit; 
            }
            $this->_model->update($row, "`id` = {$id}");
            echo $this->view->message('操作成功！', $this->view->projectUrl(array('action' => 'index'))) ;
            exit;
        }
        
        $this->renderScript('partner-tool/edit.php');
    }

    /**
     * 删除动作
     * 
     * @return void
     */
    public function deleteAction()
    {
        if ($this->_request->isPost()) {
            $ids= $this->_request->getPost('selectId');
            
            if (is_array($ids)) {
                $this->_model->deleteByIds($ids);
            }
        }
        $backUrl = urldecode($this->_request->get('backUrl'));
        redirect($backUrl);       
        exit;
    }
    /**
     * 
     * 商家订单数据与YEK平台订单数据的对比(默认时间为30天)
     */
    public function compareReportAction()
    {
        $startTime = strtotime("-1 day");
        $endTime = strtotime("-31 days");
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $product = $this->_productModel->fetchRow("code = '{$productCode}'");
        $message = '';
        
        for ($i = 0 ; $i<30 ; ++$i) {
            $currTime = date('Y-m-d', $startTime - $i*24*60*60);
            $rows[] = $this->_model->compareOrder($productCode,$currTime);
        }
        $tableHtmlCode = $this->_model->getCopareTableCode($rows);
        $message .= "
            <html>
            <head>
            <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
            <title>".date('Y-m-d',$endTime).'至'.date('Y-m-d',$startTime).$product['name']. ' 商家与Yek订单数据对比'."</title>
            <style type='text/css'>
            .table{text-align:center; background:#fff;  border-collapse:collapse;}
            .table td{padding:5px; background:#fff; font-size:12px;  border:#000 solid 1px;}
            .table .title td{background:#5081B9; color:#FFFFFF; font-weight:bold; }
            .table .number{text-align:right;}
            .table td.title{font-weight:bold;}
            .reportlink{padding:20px; width:100px; height:10px; color:#000; background:#9CB7F5; text-align:center;height:20px;line-height:20px;overflow:hidden;}
            
            .linktext{color:#000;font-size:20px;}
            </style>
            </head>
            <body>
            <p>".date('Y-m-d',$endTime).'至'.date('Y-m-d',$startTime).' '.$product['name']. ' 商家与Yek订单数据对比'."
            </p>
            <p>
            BI数据统计平台团队
            </p>
            <div>
            ".$tableHtmlCode."</div></body>
            </html>";
        //echo ($message); 
        $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/yek_mob/data/partnerTool/';
    	//$downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/data/dayData/';
    	$uploadPath = PUBLIC_PATH . "/data/partnerTool/";
        $filename = $uploadPath.$productCode.'_'.date('Ymd',$startTime).'.html';
        if (!file_exists($filename)) {
        	touch($filename);
        	chmod($filename,0777);
        } else {
        	unlink($filename);
        	touch($filename);
        	chmod($filename,0777);
        }
        if (!$handle = fopen($filename, 'a')) {
         echo "不能打开文件 ";
         exit;
        }

	    // 将$somecontent写入到我们打开的文件中。
	    if (fwrite($handle, $message) === FALSE) {
	        echo "不能写入到文件 ";
	        exit;
	    }
	    fclose($handle);
	    
        header("Content-type:text/html;charset=utf-8");
		header("Content-Disposition: attachment; filename=".$filename);
		readfile($filename);
		unlink($filename);
	    exit();
        
    }
    
    /**
     * 商家订单数据与YEK平台订单数据的对比(日报对比-按照操作系统分组)
     */
    public function compareDayReportAction()
    {
    	$filter = new Zend_Filter_StripTags();
    	//选择日期
        $startTime = $filter->filter(trim($this->_request->getPost('startTime')));
        //选择客户还是YEK还是ALL
        $type = intval($filter->filter(trim($this->_request->getPost('selectDay'))));    
        //设定描述文字
        if ($type == 1) {
        	$descMsg = ' 商家与Yek订单数据对比';
        } else if ($type == 2) {
        	$descMsg = ' 客户订单数据';
        } else if ($type == 3) {
        	$descMsg = ' Yek订单数据';
        }
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $product = $this->_productModel->fetchRow("code = '{$productCode}'");
        $message = '';
        $tableHtmlCode = $this->_model->getDayCopareTableCode($productCode, $startTime, $type);
        $message .= "
            <html>
            <head>
            <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
            <title>".date('Y年m月d日 ',strtotime($startTime)).$product['name']. $descMsg ."</title>
            <style type='text/css'>
            .table{text-align:center; background:#fff;  border-collapse:collapse;}
            .table td{padding:5px; background:#fff; font-size:12px;  border:#000 solid 1px;}
            .table .title td{background:#5081B9; color:#FFFFFF; font-weight:bold; }
            .table .number{text-align:right;}
            .table td.title{font-weight:bold;}
            .reportlink{padding:20px; width:100px; height:10px; color:#000; background:#9CB7F5; text-align:center;height:20px;line-height:20px;overflow:hidden;}
            
            .linktext{color:#000;font-size:20px;}
            </style>
            </head>
            <body>
            <p>".date('Y-m-d',strtotime($startTime)).' '.$product['name']. $descMsg."
            </p>
            <p>
            BI数据统计平台团队
            </p>
            <div>
            ".$tableHtmlCode."</div></body>
            </html>";
        //echo ($message); 
        $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/yek_mob/data/partnerTool/';
    	//$downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/data/dayData/';
    	$uploadPath = PUBLIC_PATH . "/data/partnerTool/";
        $filename = $uploadPath.$productCode.'_'.date('Ymd',strtotime($startTime)).'_dayReport.html';
        if (!file_exists($filename)) {
        	touch($filename);
        	chmod($filename,0777);
        } else {
        	unlink($filename);
        	touch($filename);
        	chmod($filename,0777);
        }
        if (!$handle = fopen($filename, 'a')) {
         echo "不能打开文件 ";
         exit;
        }

	    // 将$somecontent写入到我们打开的文件中。
	    if (fwrite($handle, $message) === FALSE) {
	        echo "不能写入到文件 ";
	        exit;
	    }
	    fclose($handle);
	    
        header("Content-type:text/html;charset=utf-8");
		header("Content-Disposition: attachment; filename=".$productCode.'_'.date('Ymd',strtotime($startTime)).'_dayReport.html');
		readfile($filename);
		unlink($filename);
	    exit(); 
    }
    
    /**
     * 商家订单数据与YEK平台订单数据的对比(月报对比-按照操作系统分组)
     */
    public function compareMonthReportAction()
    {
    	$filter = new Zend_Filter_StripTags();
    	//选择日期
        $startTime = $filter->filter(trim($this->_request->getPost('startTime')));
        $endTime = date('Y-m-1', strtotime($startTime));
        //30天之前
        //选择客户还是YEK还是ALL
        $type = intval($filter->filter(trim($this->_request->getPost('selectDay'))));    
        //设定描述文字
        if ($type == 1) {
        	$descMsg = ' 商家与Yek订单数据对比';
        } else if ($type == 2) {
        	$descMsg = ' 客户订单数据';
        } else if ($type == 3) {
        	$descMsg = ' Yek订单数据';
        }
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $product = $this->_productModel->fetchRow("code = '{$productCode}'");
        $message = '';
        
        for ($i = 1 ; $i<date('j',strtotime($startTime)) ; ++$i) {
            $currTime = date('Y-m-d', strtotime($startTime) - $i*24*60*60);
            $rows[] = $this->_model->compareMonthOrder($productCode,$currTime);
        }

        $tableHtmlCode = $this->_model->getMonthCopareTableCode($rows, $type);
        $message .= "
            <html>
            <head>
            <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
            <title>".date('Y年m月d日 ',strtotime($startTime)).$product['name']. $descMsg ."</title>
            <script src='http://bi.yekmob.com/files/admin/js/jquery.js'></script>
            <script src='http://bi.yekmob.com/files/admin/js/partnerTool/expand.js'></script>
            <style type='text/css'>
            .table{text-align:center; background:#fff;  border-collapse:collapse;}
            .table td{padding:5px; background:#fff; font-size:12px;  border:#000 solid 1px;}
            .table .title td{background:#5081B9; color:#FFFFFF; font-weight:bold; }
            .table .number{text-align:right;}
            .table td.title{font-weight:bold;}
            .reportlink{padding:20px; width:100px; height:10px; color:#000; background:#9CB7F5; text-align:center;height:20px;line-height:20px;overflow:hidden;}
            
            .linktext{color:#000;font-size:20px;}
            </style>
            </head>
            <body>
            <p>".date('Y-m-d',strtotime($endTime)).'至'.date('Y-m-d',strtotime($startTime)).' '.$product['name']. ' 商家与Yek订单数据对比'."
           </p>
            <p>
            BI数据统计平台团队
            </p>
            <div>
            ".$tableHtmlCode."</div></body>
            </html>";
        //echo ($message); 
        $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/yek_mob/data/partnerTool/';
    	//$downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/data/dayData/';
    	$uploadPath = PUBLIC_PATH . "/data/partnerTool/";
        $filename = $uploadPath.$productCode.'_'.date('Ymd',strtotime($startTime)).'_monthReport.html';
        if (!file_exists($filename)) {
        	touch($filename);
        	chmod($filename,0777);
        } else {
        	unlink($filename);
        	touch($filename);
        	chmod($filename,0777);
        }
        if (!$handle = fopen($filename, 'a')) {
         echo "不能打开文件 ";
         exit;
        }

	    // 将$somecontent写入到我们打开的文件中。
	    if (fwrite($handle, $message) === FALSE) {
	        echo "不能写入到文件 ";
	        exit;
	    }
	    fclose($handle);
        header("Content-type:text/html;charset=utf-8");
		header("Content-Disposition: attachment; filename=".$productCode.'_'.date('Ymd',strtotime($startTime)).'_monthReport.html');
		readfile($filename);
		unlink($filename);
	    exit();
    }
    /**
     * 导出商家的启动记录
     */
    public function exportBootRecordAction() {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $this->view->product = $this->_productModel->fetchRow("code = '{$productCode}'");
        $this->view->subtitle='启动次数导出';
        //收集所有存在的SOURCEID
        $this->view->sourceIds = $this->_sModel->getSourceIdByProductCode($productCode);
        if ($this->_request->isPost()) {
        	$filter = new Zend_Filter_StripTags();            
            $startTime = $filter->filter(trim($this->_request->getPost('startTime')));
            $endTime = $filter->filter(trim($this->_request->getPost('endTime')));
            $sourceId = $filter->filter(trim($this->_request->getPost('sourceId')));
            if (!$startTime or !$endTime or $startTime > $endTime) {
            	//时间不符合标准
            	echo $this->view->message('必须填写时间，并且开始时间小于等于结束时间，请重新填写！') ;
                exit;
            }
            $rows = $this->_cbeModel->getBootRecord($productCode, $startTime, $endTime, $sourceId);
            $keyAdPaidArr = array('添加时间', 'udid');
	        if ($startTime && $endTime) {
	        	if ($startTime != $endTime) {
	        		$timeMessage = $startTime . '_' . $endTime;
	        	} else {
	        		$timeMessage = $startTime;
	        	}
	        } else {
	        	$timeMessage = 'all_';
	        }
	        $adPaidFile = $this->_cbeModel->writeToExcel('client_boot', $timeMessage, $rows,$productCode,$keyAdPaidArr);
	        $path = PUBLIC_PATH . "/data/clientBoot/";
	        $filename = $path . $adPaidFile;
	        
	        header("Content-type:text/html;charset=utf-8");
			header("Content-Disposition: attachment; filename=" . $adPaidFile);
			readfile($filename);
	        
	        //文件的删除
	        @unlink($filename);
	        exit();
            
        }
    }
    /**
     * 修改每日的广告渠道点击量
     */
    public function editAdClickAction()
    {
    	$id = intval($this->_request->get('id'));
        $this->view->subtitle='修改广告渠道的点击量';
        $this->view->endTime = $startTime = date('Y-m-d',strtotime("-1 day"));
        $this->view->startTime = $endTime = date('Y-m-d',strtotime("-8 days"));
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $this->view->sources = $sources = $this->_model->getAdSource($productCode,$startTime,$endTime);
        
        if ($this->_request->isPost()) {	
            $row = array();
            foreach ($sources as $source) {
            	$sourceId = $source['sourceId'];
            	$sourceSubId = $source['sourceSubId'];  
            	$date = $source['date'];         	
            	$row['adClick'] = intval($_POST["adClick"][$sourceId][$sourceSubId][$date]);
	            if (strlen($row['adClick']) < 0) {
	            	echo $this->view->message('必须填写点击量，请重新填写！') ;
	                exit;
	            }
	            $this->_ddwModel->update($row, "`productCode`='{$productCode}' and `date`='{$date}' 
	            and `sourceId`='{$sourceId}' and `sourceSubId` = '{$sourceSubId}'");
            }
            echo $this->view->message('操作成功！', $this->view->projectUrl(array('action' => 'edit-ad-click'))) ;
            exit;
        }
    }
    
}